package rs.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import rs.domain.Track;

/* Classe responsabile dela comunicazione con il database dei tag. */
public class TagRepository {
	
	private Connection connection;
	
	public TagRepository() {
		Datasource d = new Datasource();
		this.connection = d.getConnection("rs");
	}
	
	/* Aggiunge dei tag per un certo brano. */
	public void addTags(Track track, List<String> tag_list) {
		PreparedStatement stm = null;
		
		try {			
			stm = this.connection.prepareStatement("INSERT INTO track values(?,?,?);");
			stm.setString(1, track.getName());
			stm.setString(2, track.getArtist());
			
			if (tag_list.size() > 0) {
				String tags = "";
				for (String t : tag_list) {
					tags += " " + t;
				}
				stm.setString(3, tags.substring(1));
			}
			else {
				stm.setString(3, " ");
			}
			
			stm.executeUpdate();	
			
		} catch (SQLException e) {
				try {
					if (stm != null)
						stm.close();
				} catch (SQLException e2) {
					e2.printStackTrace();
				}
			e.printStackTrace();
		}
	}
	
	/* Restituisce i tag associati ad un certo brano. */
	public List<String> getTags(Track track) {
		PreparedStatement stm = null;
		ResultSet rs = null;
		
		try {			
			stm = this.connection.prepareStatement("SELECT * FROM track WHERE name=? AND artist=?;");
			stm.setString(1, track.getName());
			stm.setString(2, track.getArtist());
			
			rs = stm.executeQuery();
			if (!rs.next()) {
				return null;
			}
			
			List<String> tags = new ArrayList<String>();
			Scanner scanner = new Scanner(rs.getString("tags"));
			while (scanner.hasNext()) {
				tags.add(scanner.next());
			}
			
			return tags;
			
		} catch (SQLException e) {
			try {
				if (stm != null)
					stm.close();
				if (rs != null)
					rs.close();
			} catch (SQLException e2) {
				e2.printStackTrace();
			}
			e.printStackTrace();
		}
		return null;
	}
	
}
